﻿using FangDuShi_Front;
using FangDuShi_Front.CommonClass;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;

namespace LawApp_API.Controllers
{

    /// <summary>
    /// 经纪人
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class RealtorController : BaseController
    {
        /// <summary>
        /// API请求地址
        /// </summary>
        private readonly string requestUrl = System.Configuration.ConfigurationManager.AppSettings["APIRequestUrl"];
        /// <summary>
        /// API的Session的Host
        /// </summary>
        private readonly string sessionHost = System.Configuration.ConfigurationManager.AppSettings["APISessionHost"];
        /// <summary>
        /// 调用内部API的授权用户信息
        /// </summary>
        private string sysUser = "admin";
        private string sysPwd = "admin";
       
        //
        // GET: /Realtor/
        public ActionResult Index()
        {
            string jsonMsg = "";

            HttpClientContext context = new HttpClientContext();

            if (Session["CookieObject"] != null)
            {
                context.Cookies = Session["CookieObject"] as CookieCollection;
            }
            else
            {
                context.Cookies = new CookieCollection();
                HttpCookie httpCookie = Request.Cookies["ASP.NET_SessionId"];
                if (httpCookie != null)
                {
                    Cookie cookie = new Cookie("ASP.NET_SessionId", httpCookie.Value);
                    cookie.Domain = sessionHost;
                    cookie.Path = "/";

                    context.Cookies.Add(cookie);

                    Session["CookieObject"] = context.Cookies;
                }
            }
            HttpWebClient webClient = new HttpWebClient(context);
            webClient.RequestUrl = requestUrl;

            JObject jObject = new JObject();
            jObject["method"] = "GetRealtorInfo";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;
            jObject["msg"] = "";

            jsonMsg = webClient.GetReturnData(jObject);

            string code = "";
            string msg = "";
            string userName = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                JObject msgObj = JObject.Parse(msg);
                userName = msgObj["FUserName"].ToString();

            }
            ViewData["username"] = userName;
            return View();
        }

        /// <summary>
        /// 经纪人登录提交
        /// </summary>
        /// <returns></returns>
        public string RealtorLogin()
        {
            string jsonMsg = "";
            string logid = Fetch.Post("txtMobile").Trim();
            string password = Fetch.Post("txtPassword").Trim();

            HttpClientContext context = new HttpClientContext();
            HttpWebClient webClient = new HttpWebClient(context);
            webClient.RequestUrl = requestUrl;
            
            JObject jObject = new JObject();
            jObject["method"] = "RealtorLogin";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;
            jObject["msg"] = "";

            JObject jObjectChild = new JObject();
            jObjectChild["logid"] = logid;
            jObjectChild["password"] = password;
            jObject["msg"] = jObjectChild.ToString();
            jsonMsg = webClient.GetReturnData(jObject);

            string code = "";
            string msg = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                Session["CookieObject"] = context.Cookies;
                
            }
           
            return jsonMsg;
        }
        /// <summary>
        /// 登录界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {

            return View();
        }
        /// <summary>
        /// 注册界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            //获取地区信息
            string jsonMsg = "";

            HttpWebClient webClient = new HttpWebClient();
            webClient.RequestUrl = requestUrl;
            JObject jObject = new JObject();
            jObject["method"] = "GetProvinceList";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;
            jObject["msg"] = "";

            jsonMsg = webClient.GetReturnData(jObject);
            string code = "";
            string msg = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                ViewData["proviceData"] = msg;
            }
            return View();
        }

        /// <summary>
        /// 获取中介公司
        /// </summary>
        /// <returns></returns>
        public string GetAgencyList()
        {
            string jsonMsg = "";

            string districtNo = Fetch.Post("districtNo").Trim();
           
            HttpWebClient webClient = new HttpWebClient();
            webClient.RequestUrl = requestUrl;
            JObject jObject = new JObject();
            jObject["method"] = "GetAgencyList";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;

            JObject jObjectChild = new JObject();
            jObjectChild["districtNo"] = districtNo;
            jObject["msg"] = jObjectChild.ToString();
            jsonMsg = webClient.GetReturnData(jObject);

            string code = "";
            string msg = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                jsonMsg = msg;
            }
            return jsonMsg;
        }
        /// <summary>
        /// 获取中介门店
        /// </summary>
        /// <returns></returns>
        public string GetAgencyBranchList()
        {
            string jsonMsg = "";

            string agencyID = Fetch.Post("agencyID").Trim();
           
            HttpWebClient webClient = new HttpWebClient();
            webClient.RequestUrl = requestUrl;
            JObject jObject = new JObject();
            jObject["method"] = "GetAgencyBranchList";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;

            JObject jObjectChild = new JObject();
            jObjectChild["agencyID"] = agencyID;
            jObject["msg"] = jObjectChild.ToString();
            jsonMsg = webClient.GetReturnData(jObject);

            string code = "";
            string msg = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                jsonMsg = msg;
            }
            return jsonMsg;
        }

        
        /// <summary>
        /// 经纪人首页
        /// </summary>
        /// <returns></returns>
        public ActionResult  RealtorInfo()
        {
            
            return View();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult Password()
        {
            //获取经纪人基本信息
            string jsonMsg = "";
            HttpClientContext context = new HttpClientContext();

            if (Session["CookieObject"] != null)
            {
                context.Cookies = Session["CookieObject"] as CookieCollection;
            }
            else
            {
                context.Cookies = new CookieCollection();
                HttpCookie httpCookie = Request.Cookies["ASP.NET_SessionId"];
                if (httpCookie != null)
                {
                    Cookie cookie = new Cookie("ASP.NET_SessionId", httpCookie.Value);
                    cookie.Domain = sessionHost;
                    cookie.Path = "/";

                    context.Cookies.Add(cookie);

                    Session["CookieObject"] = context.Cookies;
                }
            }

            HttpWebClient webClient = new HttpWebClient(context);
            webClient.RequestUrl = requestUrl;
            JObject jObject = new JObject();
            jObject["method"] = "GetRealtorInfo";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;
            jObject["msg"] = "";

            jsonMsg = webClient.GetReturnData(jObject);

            string code = "";
            string msg = "";
            string mobile = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                mobile = msgObj["FMobile"].ToString();
            }
            ViewData["FMobile"] = mobile;
            return View();
        }
        /// <summary>
        /// 修改密码保存
        /// </summary>
        /// <returns></returns>
        public string SavePassword()
        {
            string jsonMsg = "";

            string oldPassword = Fetch.Post("txtOldPassword");
            string newPassword = Fetch.Post("txtPassword");

            if (oldPassword == "")
            {
                jsonMsg = UniValidate.NotEmptyError("旧密码不能为空");
                return jsonMsg;
            }
            if (newPassword == "")
            {
                jsonMsg = UniValidate.NotEmptyError("新密码不能为空");
                return jsonMsg;
            }

            HttpClientContext context = new HttpClientContext();

            if (Session["CookieObject"] != null)
            {
                context.Cookies = Session["CookieObject"] as CookieCollection;
            }
            else
            {
                context.Cookies = new CookieCollection();
                HttpCookie httpCookie = Request.Cookies["ASP.NET_SessionId"];
                if (httpCookie != null)
                {
                    Cookie cookie = new Cookie("ASP.NET_SessionId", httpCookie.Value);
                    cookie.Domain = sessionHost;
                    cookie.Path = "/";

                    context.Cookies.Add(cookie);

                    Session["CookieObject"] = context.Cookies;
                }
            }

            HttpWebClient webClient = new HttpWebClient(context);
            webClient.RequestUrl = requestUrl;

            JObject jObject = new JObject();
            jObject["method"] = "SavePassword";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;
            jObject["msg"] = "";

            JObject jObjectChild = new JObject();
            jObjectChild["oldPassword"] = oldPassword;
            jObjectChild["newPassword"] = newPassword;
            jObject["msg"] = jObjectChild.ToString();
            jsonMsg = webClient.GetReturnData(jObject);

            string code = "";
            string msg = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                

            }

            return jsonMsg;
        }
        /// <summary>
        /// 获取手机验证码
        /// </summary>
        /// <returns></returns>
        public string GetMobileCAPTCHA()
        {
            string returnMsg = "";
            string mobileNo = Fetch.Post("mobileNo").Trim();
            string ipAddress = FangDuShi_Front.Common.GenerateUtil.GetClientIPv4Address();

            HttpWebClient webClient = new HttpWebClient();
            webClient.RequestUrl = requestUrl;
            JObject jObject = new JObject();
            jObject["method"] = "GetMobileCAPTCHA";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;

            JObject jObjectChild = new JObject();
            jObjectChild["mobileNo"] = mobileNo;
            jObjectChild["ipAddress"] = ipAddress;

            jObject["msg"] = jObjectChild.ToString();
            
            returnMsg = webClient.GetReturnData(jObject);

            return returnMsg;
        }

        /// <summary>
        /// 注册保存
        /// </summary>
        /// <returns></returns>
        public string Save()
        {
            string jsonMsg = "";

            //检查账号是否已经注册
            string r_txtMobile = Fetch.Post("r_txtMobile");
            string r_txtMobileCAPTCHA = Fetch.Post("r_txtMobileCAPTCHA");
            string r_txtPassword= Fetch.Post("r_txtPassword");
            string r_txtRealName=Fetch.Post("r_txtRealName");
            string r_txtDistrictNo = Fetch.Post("r_txtDistrictNo");
            string r_chkIsAlone = Fetch.Post("r_chkIsAlone");
            string r_chkIsAccept = Fetch.Post("r_chkIsAccept");
            string r_txtAgency = Fetch.Post("r_txtAgency");
            string r_txtAgencyBranch = Fetch.Post("r_txtAgencyBranch");
            if (r_txtMobile == "")
            {
                jsonMsg = UniValidate.NotEmptyError("手机号码不能为空");
                return jsonMsg;
            }
            if (r_txtPassword == "")
            {
                jsonMsg = UniValidate.NotEmptyError("密码不能为空");
                return jsonMsg;
            }
             if (r_txtMobileCAPTCHA == "")
            {
                jsonMsg = UniValidate.NotEmptyError("手机验证码不能为空");
                return jsonMsg;
            }
            if (r_txtRealName == "")
            {
                jsonMsg = UniValidate.NotEmptyError("真实姓名不能为空");
                return jsonMsg;
            }
            if (r_txtDistrictNo == "" || r_txtDistrictNo == "-1")
            {
                jsonMsg = UniValidate.NotEmptyError("请选择所在城市");
                return jsonMsg;
            }
            if (r_chkIsAccept == "")
            {
                jsonMsg = UniValidate.NotEmptyError("请阅读同意注册协议");
                return jsonMsg;
            }
            if (r_txtAgency == "")
            {
                jsonMsg = UniValidate.NotEmptyError("所属公司不能为空");
                return jsonMsg;
            }
            if (r_txtAgencyBranch == "")
            {
                jsonMsg = UniValidate.NotEmptyError("所在门店不能为空");
                return jsonMsg;
            }

            HttpWebClient webClient = new HttpWebClient();
            webClient.RequestUrl = requestUrl;
            JObject jObject = new JObject();
            jObject["method"] = "CheckMobileCanReg";
            jObject["sysUser"] = sysUser;
            jObject["sysPwd"] = sysPwd;

            JObject jObjectChild = new JObject();
            jObjectChild["mobileNo"] = r_txtMobile;

            jObject["msg"] = jObjectChild.ToString();

            
            jsonMsg = webClient.GetReturnData(jObject);

            string code = "";
            string msg = "";
            FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code == "0")
            {
                //判断手机验证码
                jObject = new JObject();
                jObject["method"] = "CheckMobileCAPTCHA";
                jObject["sysUser"] = sysUser;
                jObject["sysPwd"] = sysPwd;
                jObjectChild = new JObject();
                jObjectChild["mobileNo"] = r_txtMobile;
                jObjectChild["mobileCAPTCHA"] = r_txtMobileCAPTCHA;
                jObject["msg"] = jObjectChild.ToString();


                jsonMsg = webClient.GetReturnData(jObject);
                FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                if (code == "0")
                {
                    //检测所在公司和所在门店是否有效
                    jObject = new JObject();
                    jObject["method"] = "CheckAgencyAndBranch";
                    jObject["sysUser"] = sysUser;
                    jObject["sysPwd"] = sysPwd;
                    jObjectChild = new JObject();
                    jObjectChild["agencyBriefName"] = r_txtAgency;
                    jObjectChild["branchBriefName"] = r_txtAgencyBranch;
                    jObject["msg"] = jObjectChild.ToString();
                    jsonMsg = webClient.GetReturnData(jObject);
                    FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                    if (code == "0")
                    {
                        decimal tmpDecimal = 0;
                        if (!decimal.TryParse(msg, out tmpDecimal))
                        {
                            jsonMsg = UniValidate.NotEmptyError("所在公司或者门店不存在");
                            return jsonMsg;
                        }

                        //发送注册信息
                        FangDuShi_Front.Model.Realtor realtorModel = new FangDuShi_Front.Model.Realtor();
                        realtorModel.FMobile = r_txtMobile;
                        realtorModel.FAgencyBranchID = tmpDecimal;
                        realtorModel.FDistrictNo = r_txtDistrictNo;
                        realtorModel.FIsAloneRealtor = r_chkIsAlone == "on" ? "Y" : "N";
                        realtorModel.FMobile = r_txtMobile;
                        realtorModel.FPassword = FangDuShi_Front.Common.MD5.MD5Encrypt(realtorModel.FMobile + r_txtPassword);
                        realtorModel.FRealName = r_txtRealName;
                        realtorModel.FRegIP = FangDuShi_Front.Common.GenerateUtil.GetClientIPv4Address();
                        realtorModel.FSex = "男";
                        jObject = new JObject();
                        jObject["method"] = "RealtorRegSave";
                        jObject["sysUser"] = sysUser;
                        jObject["sysPwd"] = sysPwd;
                        JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
                        {
                           // DateFormatHandling = DateFormatHandling.IsoDateFormat,
                            NullValueHandling = NullValueHandling.Ignore
                        };

                        jObjectChild = new JObject();
                        jObjectChild["model"] = JsonConvert.SerializeObject(realtorModel, microsoftDateFormatSettings); ;
                        jObjectChild["mobileCAPTCHA"] = r_txtMobileCAPTCHA;
                        jObject["msg"] = jObjectChild.ToString();

                        jsonMsg = webClient.GetReturnData(jObject);
                        FangDuShi_Front.Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                        if (code != "0")
                        {
                            jsonMsg = msg;
                        }
                    }

                }

            }
            return jsonMsg;
        }

       
	}
}